package com.day1018;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

public class PhoneText {
    public static void main(String[] args) throws Exception {
        //  得到document解析器的工厂实例  -----单例设计模式
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //   从DOM工厂获得DOM解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        //  解析xml文档  ， 得到一个Document对象，即DOM树
        Document doc = (Document) db.parse("D:\\IDEA\\lzy_java\\src\\main\\java\\com\\day1018\\phone.xml");
        NodeList nodeList = doc.getElementsByTagName("phoneInfo");
        Node node = nodeList.item(0);
        NodeList childList = node.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            Node child = childList.item(i);
            if (child.getNodeType() == 1){
                System.out.println("标签名：" + child.getNodeName());
                Node nameName = child.getAttributes().getNamedItem("name");
                System.out.println("name属性名：" + nameName.getNodeValue());
                NodeList typeList1 = child.getChildNodes();
                for (int j = 0; j < typeList1.getLength(); j++) {
                    Node typenode1 = typeList1.item(j);
                    if (typenode1.getNodeType() == 1){
                        System.out.println("标签名：" + typenode1.getNodeName());
                        Node typenameName = typenode1.getAttributes().getNamedItem("name");
                        System.out.println("name属性名：" + typenameName.getNodeValue());
                    }
                }

            }
        }
        Element brand = doc.createElement("Brand");
        brand.setAttribute("name","小米");
        Element type = doc.createElement("Type");
        type.setAttribute("name","小米10");
        brand.appendChild(type);
        node.appendChild(brand);
        ///   重新写入 新文件当中
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer =factory.newTransformer();
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\IDEA\\lzy_java\\src\\main\\java\\com\\day1018\\phone1.xml");
        //OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"GB2312");
        StreamResult streamResult = new StreamResult(fileOutputStream);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source,streamResult);

    }
}
